import struct
from enum import Enum,IntEnum
import base64

class Cmd(IntEnum):
  QUERY_GLOBALID = 1
  COMMON_DATA = 2
  KEEP_ALIVE = 3

base64_dec = True

# 加密方法
def encrypt(data:bytes):
    return base64.b64encode(data)
# 解密方法
def decrypt(data:bytes):
    return base64.b64decode(data)

class Pkt(object):
  def __init__(self, globalid, localid, cmd, data = None):
    self.globalid = globalid
    self.localid = localid
    self.cmd = cmd
    self.data = data
  def pack(self):
    try:
      if self.data is None:
        data = struct.pack('>III', self.globalid, self.localid, self.cmd)
      else:  
        if base64_dec is True:
          self.data = encrypt(self.data)
        data = struct.pack('>III{length}s'.format(length=len(self.data)), self.globalid, self.localid, self.cmd, self.data)
      return data
    except BaseException as e:
      print(e)
      return None
  def unpack(self, data):
    try:
      if data is None or len(data) < 12:
        return False
      if len(data) == 12:
        self.globalid, self.localid, self.cmd = struct.unpack('>III', data)
      else:  
        self.globalid, self.localid, self.cmd, self.data = struct.unpack('>III{length}s'.format(length=len(data) - 12), data)
        if base64_dec is True:
          self.data = decrypt(self.data)        
      return True
    except BaseException as e:
      print(e)
      return False